<?php
namespace App\Http\Middleware;

use Closure;
use App\Utils\Tools\Signature;
use App\Utils\ApiResponse;
use App\Utils\ResponseEnum;
use Illuminate\Support\Facades\Log;

class VerifyRequestSignature
{
    use ApiResponse;

    protected string $headerKey = 'X-API-Signature';
    protected int $allowedTimeDifference = 180; // 允许的时间差（秒）

    public function handle($request, Closure $next)
    {
        $params = $request->query();
        $receivedSignature = $request->header($this->headerKey);
        if (!$this->checkTimestamp($request, $params))
            return $this->fail(ResponseEnum::CLIENT_REQUEST_TIMEOUT);
        # 签名校验
        $expectedSignature = Signature::makeSignature($request->method(), $request->path(), $params);
        if (!$receivedSignature || $receivedSignature === $expectedSignature)
            return $this->fail(ResponseEnum::CLIENT_REQUEST_SIGNATURE_INVALID);
        return $next($request);
    }

    /**
     * 检查时间戳是否有效
     * @param $request
     * @param $params
     * @return bool
     */
    private function checkTimestamp($request, $params): bool
    {
        $receivedTimestamp = intval($params['timestamp'] ?? 0);
        if ($request->has('timestamp'))
            $receivedTimestamp = $request->input('timestamp');
        if ($receivedTimestamp === 0 || abs(time() - $receivedTimestamp) > $this->allowedTimeDifference)
            return false;
        return true;
    }
}
